import com.sun.xml.internal.ws.api.model.wsdl.WSDLOutput;

import java.util.concurrent.PriorityBlockingQueue;

//模拟实现一个定时器
class MyTask implements Comparable<MyTask>{
    public Runnable runnable;
    public long time;

    public MyTask(Runnable runnable, long delay){
        this.runnable = runnable;
        this.time = System.currentTimeMillis() + delay;
    }


    @Override
    public int compareTo(MyTask o) {
        return (int)(this.time - o.time);
    }
}

class MyTimer{
    private PriorityBlockingQueue<MyTask> queue = new PriorityBlockingQueue<>();
    private Object locker = new Object();

    public void schedule(Runnable runnable, long delay){
        MyTask myTask = new MyTask(runnable, delay);
        queue.put(myTask);
        synchronized (locker){
            locker.notify();
        }
    }

    //在构造方法内创建一个线程！
    public MyTimer(){
        Thread t = new Thread(() -> {
            while(true){
                try {
                    synchronized (locker){
                        MyTask myTask = queue.take();
                        long current = System.currentTimeMillis();
                        if(myTask.time > current ){
                            queue.put(myTask);
                            locker.wait(myTask.time - current );
                        }else{
                            myTask.runnable.run();
                        }
                    }

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        });
        t.start();
    }

}
public class ThreadDemo1 {
    public static void main(String[] args) {
        MyTimer myTimer = new MyTimer();
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("♥♥♥♥♥♥");
            }
        },1500 );
        System.out.println("♥♥♥");
    }
}
